from functools import wraps
from rest_framework.exceptions import PermissionDenied

def require_role(roles):
    def decorator(view_func):
        @wraps(view_func)
        def _wrapped_view(view_instance, request, *args, **kwargs):
            if not request.user.is_authenticated:
                raise PermissionDenied('请先登录')
            
            if isinstance(roles, str):
                roles_list = [roles]
            else:
                roles_list = roles
                
            if request.user.role not in roles_list:
                raise PermissionDenied('您没有权限执行此操作')
                
            return view_func(view_instance, request, *args, **kwargs)
        return _wrapped_view
    return decorator

def require_purchase_permission(view_func):
    @wraps(view_func)
    def _wrapped_view(view_instance, request, *args, **kwargs):
        if not request.user.has_purchase_permission():
            raise PermissionDenied('您没有采购权限')
        return view_func(view_instance, request, *args, **kwargs)
    return _wrapped_view

def require_sales_permission(view_func):
    @wraps(view_func)
    def _wrapped_view(view_instance, request, *args, **kwargs):
        if not request.user.has_sales_permission():
            raise PermissionDenied('您没有销售权限')
        return view_func(view_instance, request, *args, **kwargs)
    return _wrapped_view

def require_delivery_permission(view_func):
    @wraps(view_func)
    def _wrapped_view(view_instance, request, *args, **kwargs):
        if not request.user.has_delivery_permission():
            raise PermissionDenied('您没有配送权限')
        return view_func(view_instance, request, *args, **kwargs)
    return _wrapped_view

def require_supplier_permission(view_func):
    @wraps(view_func)
    def _wrapped_view(view_instance, request, *args, **kwargs):
        if not request.user.has_supplier_permission():
            raise PermissionDenied('您没有供应商权限')
        return view_func(view_instance, request, *args, **kwargs)
    return _wrapped_view

def require_customer_permission(view_func):
    @wraps(view_func)
    def _wrapped_view(view_instance, request, *args, **kwargs):
        if not request.user.has_customer_permission():
            raise PermissionDenied('您没有客户权限')
        return view_func(view_instance, request, *args, **kwargs)
    return _wrapped_view 